import {
  ref
} from 'vue'

// 创建链表式焦点导航器
export function createFocusNavigator(items, initialIndex = 0) {
  // 当前焦点索引
  const currentIndex = ref(initialIndex);
  
  // 长按阈值（仅用于防止误触）
  const LONG_PRESS_THRESHOLD = 300;
  
  // 按键信息存储
  const keyPressInfo = ref({});

  // 移动到下一个焦点（向下/向右）
  const moveToNext = () => {
    if (items && items.length > 0) {
      currentIndex.value = (currentIndex.value + 1) % items.length;
      console.log(`焦点移动到下一个: ${currentIndex.value}, 总数: ${items.length}`);
    }
  };

  // 移动到上一个焦点（向上/向左）
  const moveToPrevious = () => {
    if (items && items.length > 0) {
      currentIndex.value = currentIndex.value === 0 ? items.length - 1 : currentIndex.value - 1;
      console.log(`焦点移动到上一个: ${currentIndex.value}, 总数: ${items.length}`);
    }
  };

  // 获取当前焦点位置信息
  const getCurrentPosition = () => {
    const item = items[currentIndex.value];
    return item ? item.position : { row: 0, col: 0 };
  };

  // 按键抬起处理
  const handleKeyUp = (event) => {
    const keyCode = event.keyCode;
    
    // 处理确认键（DPAD_CENTER）
    if (keyCode === 23) {
      const currentItem = items[currentIndex.value];
      if (currentItem && currentItem.onSelect) {
        currentItem.onSelect(currentItem, currentIndex.value);
      }
      return;
    }
    
    const info = keyPressInfo.value[keyCode];
    if (!info) return;

    // 清理按键信息
    if (info.timer) clearTimeout(info.timer);
    delete keyPressInfo.value[keyCode];

    // 短按处理：上下键直接移动焦点
    if (!info.longPressTriggered) {
      if (keyCode === 19) { // KEYCODE_DPAD_UP
        moveToPrevious();
      } else if (keyCode === 20) { // KEYCODE_DPAD_DOWN
        moveToNext();
      }
    }
  };

  // 按键按下处理
  const handleKeyDown = (event) => {
    const keyCode = event.keyCode;
    
    // 只处理上下键
    if (keyCode !== 19 && keyCode !== 20) return;
    
    // 防止重复处理
    if (keyPressInfo.value[keyCode]) return;

    // 设置长按定时器（仅用于防止误触，不执行额外动作）
    const timer = setTimeout(() => {
      if (keyPressInfo.value[keyCode]) {
        keyPressInfo.value[keyCode].longPressTriggered = true;
        console.log('长按检测完成，防止误触');
      }
    }, LONG_PRESS_THRESHOLD);

    keyPressInfo.value[keyCode] = {
      timer,
      longPressTriggered: false
    };
  };

  // 清理函数
  const destroy = () => {
    Object.values(keyPressInfo.value).forEach(info => {
      if (info.timer) clearTimeout(info.timer);
    });
    keyPressInfo.value = {};
  };

  // 设置焦点到指定索引
  const setFocus = (index) => {
    if (items && index >= 0 && index < items.length) {
      currentIndex.value = index;
      console.log(`焦点设置到: ${index}`);
    }
  };

  // 获取当前焦点索引
  const getCurrentIndex = () => currentIndex.value;

  // 初始化时输出调试信息
  console.log(`焦点导航器初始化: 初始索引=${initialIndex}, 项目总数=${items ? items.length : 0}`);

  return {
    handleKeyDown,
    handleKeyUp,
    destroy,
    getCurrentPosition,
    getCurrentIndex,
    setFocus,
    currentIndex
  };
}